# 数据结构和算法

# 1.1 解压序列赋值给多个变量

# 现在有一个包含 N 个元素的元组或者是序列，怎样将它里面的值解压后同时赋值给 N 个变量？
data = ['ACME', 50, 91.1, (2012, 12, 21)]
name, shares, price, date = data
print(date)  # (2012, 12, 21)
name, shares, price, (year, mon, day) = data
print(day)  # 21

s = 'Hello'
a, b, c, d, e = s
print(e)  # o

# 你可能只想解压一部分，丢弃其他的值 可以使用任意变量名去占位
data = ['ACME', 50, 91.1, (2012, 12, 21)]
_, shares, price, _ = data
print(price)

# 1.2 解压可迭代对象赋值给多个变量
record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
name, email, *phone_numbers = record
print(phone_numbers)  # ['773-555-1212', '847-555-1212']

# 1.3 保留最后 N 个元素
from collections import deque

q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)  # deque([1, 2, 3], maxlen=3)
q.append(4)
print(q)  # deque([2, 3, 4], maxlen=3)

# 1.4 查找最大或最小的 N 个元素
import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums))  # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums))  # Prints [-4, 1, 2]

# 1.6 字典中的键映射多个值
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = {}
for k, v in s:
    d.setdefault(k, []).append(v)
print('\n', d)  # {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}
a = sorted(d.items())
print('\n', a)  # [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

# 1.8 字典的运算
prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')

# 1.16 过滤序列元素
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
print([n for n in mylist if n > 0])

# 1.17 从字典中提取子集
prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
# Make a dictionary of all prices over 200
p1 = {key: value for key, value in prices.items() if value > 200}
# Make a dictionary of tech stocks

tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
p2 = {key: value for key, value in prices.items() if key in tech_names}
